/*
 * Copyright 2019-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dx.financehy.modules.security.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.dx.financehy.modules.security.config.bean.LoginProperties;
import com.dx.financehy.modules.security.config.bean.SecurityProperties;
import com.dx.financehy.modules.security.domain.dto.JwtUserDto;
import com.dx.financehy.utils.RedisUtils;
import com.dx.financehy.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: liaojinlong
 * @date: 2020/6/11 18:01
 * @apiNote: 用于清理 用户登录信息缓存，为防止Spring循环依赖与安全考虑 ，单独构成工具类
 */
@Component
public class UserCacheManager {

    @Resource
    private RedisUtils redisUtils;
    @Value("${login.user-cache.idle-time}")
    private long idleTime;
    @Resource
    private SecurityProperties properties;


    /**
     * 返回用户缓存
     *
     * @param userName 用户名
     * @return JwtUserDto
     */
    public JwtUserDto getUserCache(String userName) {
        if (StringUtils.isNotEmpty(userName)) {
            // 获取数据
            Object obj = redisUtils.hget(LoginProperties.cacheKey, userName);
            if (obj != null) {
                return (JwtUserDto) obj;
            }
        }
        return null;
    }

    /**
     * 添加缓存到Redis
     *
     * @param userName 用户名
     */
//    @Async
    public void addUserCache(String userName, JwtUserDto user) {
        if (StringUtils.isNotEmpty(userName)) {
            // 添加数据, 避免数据同时过期
            long time = idleTime + RandomUtil.randomInt(900, 1800);
            redisUtils.hset(LoginProperties.cacheKey, userName, user, time);
        }
    }

    /**
     * 清理特定用户缓存信息<br>
     * 用户信息变更时
     *
     * @param userName /
     */
    public void cleanUserCache(String userName) {
        if (StringUtils.isNotEmpty(userName)) {
            // 清除数据
            redisUtils.hdel(LoginProperties.cacheKey, userName);
        }
    }

    public void cleanBatchUserCache(List<String> key) {
        if (key.size() > 0) {
            // 清除数据
            redisUtils.hmdel(LoginProperties.cacheKey, key);
        }
    }

    /**
     * 清理当前登录用户对应的token
     *
     * @param token
     */
    public void cleanToken(String token) {
        redisUtils.del(properties.getOnlineKey() + token);
    }

    /**
     * 清理当前登录用户对应的token
     *
     * @param request
     */
    public String getToken(HttpServletRequest request) {
        String requestHeader = request.getHeader(properties.getHeader());
        if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) {
            // 去掉令牌前缀
            return StrUtil.subAfter(requestHeader, properties.getTokenStartWith(), false);
        } else {
            return null;
        }
    }

}
